package com.se.xb.dao;

import com.se.xb.entity.Article;
import com.se.xb.entity.User;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class ArticleDao extends BaseDao {
    public List<Article> getArticleList(Integer currentPage, String... query) {
        String userid = query[0];
        String title = query[1];
        String sql = "";
        Integer Start = (currentPage - 1) * 3;
        Integer End = 3;
        List<Article> articles = null;
        if (Objects.equals(title, "")) {
            sql = "SELECT * FROM article LIMIT ?, ?";
            try {
                articles = jdbcTemplate.query(sql, new Object[]{Start, End}, new BeanPropertyRowMapper<>(Article.class));
            } catch (Exception e) {
                // 更详细的异常处理
                System.out.println("Error occurred while fetching user: " + e.getMessage());
                // 可以选择记录日志、抛出自定义异常等
                return null; // 或者根据业务需求返回默认值或抛出异常
            }
        } else {
            sql = "SELECT * FROM article where title like ? LIMIT ?, ?";
            try {
                articles = jdbcTemplate.query(sql, new Object[]{"%" + title + "%", Start, End}, new BeanPropertyRowMapper<>(Article.class));
            } catch (Exception e) {
                // 更详细的异常处理
                System.out.println("Error occurred while fetching user: " + e.getMessage());
                // 可以选择记录日志、抛出自定义异常等
            }
        }
        return articles;
    }

    public Integer getArticleCount(String... query) {
        String userid = query[0];
        String title = query[1];
        String sql = "";
        Integer count = 0;
        sql = "SELECT count(*) FROM article ";
        if (!Objects.equals(title, "")) {
            sql += "where title like ?";
            try {
                count = jdbcTemplate.queryForObject(sql, new Object[]{"%" + title + "%"}, Integer.class);
            } catch (Exception e) {
                // 更详细的异常处理
                System.out.println("Error occurred while fetching user: " + e.getMessage());
                // 可以选择记录日志、抛出自定义异常等
            }
            return count;
        }
        try {
            count = jdbcTemplate.queryForObject(sql, Integer.class);
        } catch (Exception e) {
            // 更详细的异常处理
            System.out.println("Error occurred while fetching user: " + e.getMessage());
            // 可以选择记录日志、抛出自定义异常等
        }
        return count;
    }

    public Article getArticle(Long id) {
        String sql = "SELECT * FROM article where id = ?";
        Article article = null;
        try {
            article = jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<>(Article.class));
        } catch (Exception e) {
            // 更详细的异常处理
            System.out.println("Error occurred while fetching user: " + e.getMessage());
            // 可以选择记录日志、抛出自定义异常等
        }
        return article;
    }

    public Map<String, Integer> getFavoriteLikes(Long userId) {
        // SQL语句：获取用户收藏的文章及其喜欢人数
        String sql = "SELECT a.id AS article_id, COUNT(f.u_id) AS likes_count " +
                "FROM article a " +
                "JOIN favorite f ON a.id = f.a_id " +
                "WHERE f.u_id = ? " +
                "GROUP BY a.id";

        // 使用JdbcTemplate查询结果
        List<Map<String, Object>> results = jdbcTemplate.queryForList(sql, userId);

        // 将结果转换为Map<String, Integer>，其中key为文章ID，value为喜欢人数
        Map<String, Integer> articleLikesMap = new HashMap<>();
        for (Map<String, Object> row : results) {
            String articleId = row.get("article_id").toString(); // 文章ID
            Integer likesCount = Integer.parseInt(row.get("likes_count").toString()); // 喜欢人数
            articleLikesMap.put(articleId, likesCount);
        }

        return articleLikesMap;
    }

    public Integer getFavoriteCount(Long id) {
        String sql = "SELECT COUNT(*) FROM favorite WHERE a_id = ?";
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(sql, new Object[]{id}, Integer.class);
        } catch (Exception e) {
            // 更详细的异常处理
            System.out.println("Error occurred while fetching user: " + e.getMessage());
            // 可以选择记录日志、抛出自定义异常等
        }
        return count;
    }


    public void updateArticle(Article article) {
        String sql = "UPDATE article SET title = ?, content = ?, browse_count = ?, publish_date = ? WHERE id = ?";
        try {
            jdbcTemplate.update(sql, article.getTitle(), article.getContent(), article.getBrowseCount(), article.getPublishDate(), article.getId());
        } catch (DataAccessException e) {
            System.out.println("Error occurred while updating article: " + e.getMessage());
        }
    }

    public List<Article> getFavoriteList(Long userId) {
        String sql = "SELECT a.* FROM article a JOIN favorite f ON a.id = f.a_id WHERE f.u_id = ?";
        List<Article> articles = null;
        try {
            articles = jdbcTemplate.query(sql, new Object[]{userId}, new BeanPropertyRowMapper<>(Article.class));
        } catch (DataAccessException e) {
            throw new RuntimeException(e);
        }
        return articles;
    }

    public List<Article> getFavoriteList(Integer currentPage, String... query) {
        String userid = query[0];
        String title = query[1];
        String sql = "";
        Integer Start = (currentPage - 1) * 3;
        Integer End = 3;
        List<Article> articles = null;
        if (Objects.equals(title, "")) {
            sql = "SELECT * FROM article where id in (select a_id from favorite where u_id = ?) LIMIT ?,?";
            try {
                articles = jdbcTemplate.query(sql, new Object[]{userid, Start, End}, new BeanPropertyRowMapper<>(Article.class));
            } catch (Exception e) {
                // 更详细的异常处理
                System.out.println("Error occurred while fetching user: " + e.getMessage());
                // 可以选择记录日志、抛出自定义异常等
                return null; // 或者根据业务需求返回默认值或抛出异常
            }
        } else {
            sql = "SELECT * FROM article where id in (select a_id from favorite where u_id = ?) and title like ? LIMIT ?, ?";
            try {
                articles = jdbcTemplate.query(sql, new Object[]{userid, "%" + title + "%", Start, End}, new BeanPropertyRowMapper<>(Article.class));
            } catch (Exception e) {
                // 更详细的异常处理
                System.out.println("Error occurred while fetching user: " + e.getMessage());
                // 可以选择记录日志、抛出自定义异常等
                return null; // 或者根据业务需求返回默认值或抛出异常
            }
        }
        return articles;
    }

    public Integer getFavoriteArticleCount(Long userId, String title) {
        String sql = null;
        Integer count = 0;
        if (Objects.equals(title, "")) {
            sql = "SELECT COUNT(*) FROM article a JOIN favorite f ON a.id = f.a_id WHERE f.u_id = ?";
        } else {
            sql = "SELECT COUNT(*) FROM article a JOIN favorite f ON a.id = f.a_id WHERE f.u_id = ? and title like ?";
        }
        try {
            count = jdbcTemplate.queryForObject(sql, new Object[]{userId}, Integer.class);
        } catch (Exception e) {
            // 更详细的异常处理
            System.out.println("Error occurred while fetching user: " + e.getMessage());
            // 可以选择记录日志、抛出自定义异常等
        }
        return count;
    }

    public void addArticle(Article article) {
        String sql = "INSERT INTO article (title, content, browse_count, publish_date, publish_real_name, user_id) VALUES (?, ?, ?, ?, ?,?)";
        try {
            jdbcTemplate.update(sql, article.getTitle(), article.getContent(), article.getBrowseCount(), article.getPublishDate(), article.getPublishRealName(), article.getUserId());
        } catch (DataAccessException e) {
            System.out.println("Error occurred while adding article: " + e.getMessage());
        }
    }

    public void favorite(Long userId, Long articleId) {
        String sql = "INSERT INTO favorite (u_id, a_id) VALUES (?, ?)";
        try {
            jdbcTemplate.update(sql, userId, articleId);
        }catch (DataAccessException e){
            System.out.println("Error occurred while adding article: " + e.getMessage());
        }
    }

    public void unfavorite(Long userId, Long articleId) {
        String sql = "DELETE FROM favorite WHERE u_id = ? AND a_id = ?";
        try {
            jdbcTemplate.update(sql, userId, articleId);
        }catch (DataAccessException e){
            System.out.println("Error occurred while adding article: " + e.getMessage());
        }
    }
}
